<template>
  <div class="wx_detail">
    <!-- 1.企微用户 非crm客户 -->
    <div v-if="customerData && !customerData.customerId" class="customer-container">
      <div class="customer-info-card">
        <div class="card-header">
          <div class="header-content">
            <div class="user-avatar">
              <Icon icon="ep:user" class="avatar-icon" />
            </div>
            <div class="user-basic-info">
              <h3 class="user-name">{{ customerData.name }}</h3>
              <p class="corp-name">{{ customerData.corpName || '暂无企业信息' }}</p>
            </div>
          </div>
        </div>

        <div class="card-body">
          <el-descriptions :column="1" class="custom-descriptions">
            <el-descriptions-item label="用户名称" class="desc-item">
              <span class="user-name-text">{{ customerData.name }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="所在企业" class="desc-item">
              <span class="corp-text">{{ customerData.corpName || '-' }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="添加时间" class="desc-item">
              <span class="time-text">{{ formatDate(customerData.createTime) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="上次聊天时间" class="desc-item">
              <span class="time-text">{{ formatDate(customerData.lastChatTime) || '-' }}</span>
            </el-descriptions-item>
          </el-descriptions>

          <div class="opera-btn">
            <el-button type="primary" @click="tranCustomer" class="transfer-btn">
              <Icon icon="ep:user-filled" class="btn-icon" />
              转为客户
            </el-button>
          </div>
        </div>
      </div>

      <!-- 用户跟进 -->
      <div class="follow-section">
        <div class="section-title">
          <Icon icon="ep:list" class="title-icon" />
          <span>跟进记录</span>
        </div>

        <div class="follow-list">
          <div
            class="follow-item"
            v-for="(item, index) in customerData.followUserList"
            :key="index"
          >
            <div class="follow-header">
              <div class="follow-user">
                <div class="user-avatar-small">
                  <Icon icon="ep:avatar" class="avatar-icon-small" />
                </div>
                <div class="user-info">
                  <h4 class="user-nickname">{{ item.userNickname }}</h4>
                  <p class="user-level">
                    第{{
                      item.level == 0
                        ? '一'
                        : (Number(item.level) + 1).toLocaleString('zh-CN', {
                            style: 'decimal',
                            minimumFractionDigits: 0
                          })
                    }}负责人
                  </p>
                </div>
              </div>
              <div class="follow-time">
                {{ formatDate(item.createTime) }}
              </div>
            </div>

            <div class="follow-content">
              <el-descriptions :column="1" class="follow-descriptions">
                <el-descriptions-item label="企业员工" class="follow-desc-item">
                  <span class="desc-value">{{ item.userNickname }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="跟进人等级" class="follow-desc-item">
                  <span class="level-badge">
                    第{{
                      item.level == 0
                        ? '一'
                        : (Number(item.level) + 1).toLocaleString('zh-CN', {
                            style: 'decimal',
                            minimumFractionDigits: 0
                          })
                    }}负责人
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间" class="follow-desc-item">
                  <span class="desc-value">{{ formatDate(item.createTime) }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="备注的手机号" class="follow-desc-item">
                  <span class="phone-text">{{ item.remarkMobiles || '-' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="备注的企业名称" class="follow-desc-item">
                  <span class="desc-value">{{ item.remarkCorpName || '-' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="客户备注" class="follow-desc-item">
                  <span class="remark-text">{{ item.remark || '-' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="客户描述" class="follow-desc-item">
                  <span class="desc-text">{{ item.description || '-' }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="添加场景" class="follow-desc-item">
                  <span class="scene-tag">{{ wayList[item.addWay] || '未知' }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="customerData && customerData.customerId">
      <Sip :weCom="true" />
      <CustomerH5 :customerId="customerData.customerId" />
    </div>
    <div v-if="!customerData">
      <el-empty description="暂未同步"></el-empty>
      <div class="text-center">
        <el-button type="primary" @click="handleSyncUser">同步企微客户</el-button>
      </div>
    </div>
  </div>
  <CustomerForm ref="customerForm" @success="bindCustomer" />
</template>

<script setup>
import {
  getWeCustomerId,
  getCustomerTag,
  bindCustomerApi,
  syncUser
} from '@/api/wecom/customer/index'
import Sip from '@/layout/components/Sip/index.vue'
import * as ww from '@wecom/jssdk'
import * as WeComApiConfigApi from '@/api/wecom/apiconfig'
import CustomerForm from '@/views/crm/customer/CustomerForm.vue'
import { formatDate } from '@/utils/formatTime'
import CustomerH5 from '@/components/CrmSpec/CrmSpecH5.vue'

const formData = ref()
const jsapiSignature = ref(null)
const customerForm = ref(null)
const wayList = {
  0: '未知来源',
  1: '扫码二维码',
  2: '搜索手机号',
  3: '名片分享',
  4: '群聊',
  5: '手机通讯录',
  6: '微信联系人',
  8: '安装第三方应用时自动添加的客服人员',
  9: '搜索邮箱',
  10: '视频号添加',
  11: '通过日程参与人添加',
  12: '通过会议参与人添加',
  13: '添加微信还有对应的企业微信',
  14: '通过智慧硬件专属客服添加',
  15: '通过上门服务客服添加',
  16: '通过获客链接添加',
  17: '通过定制开发添加',
  18: '通过需求回复添加',
  21: '通过第三方售前客服添加',
  22: '通过可能的商务伙伴添加',
  24: '通过接收微信账号收到的好友申请添加',
  201: '内部成员共享',
  202: '管理员/负责人分配'
}
const getAgentConfigSignature = async () => {
  return ww.getSignature(jsapiSignature.value.jsapiTicket)
}
// 1.设置
const getWeComApiConfig = async () => {
  formData.value = await WeComApiConfigApi.getWeComApiConfig()
  jsapiSignature.value = await WeComApiConfigApi.getJsapiSignature({
    url: window.location.href
  })
  initComponentSession()
}
const wxUserId = ref(null)
// 2.获取userId
const initComponentSession = async () => {
  try {
    ww.register({
      corpId: formData.value.corpId,
      agentId: formData.value.agentId,
      jsApiList: ['getCurExternalContact'],
      getAgentConfigSignature
    })
    wx.agentConfig({
      corpid: formData.value.corpId,
      agentid: formData.value.agentId,
      timestamp: Math.floor(Date.now() / 1000),
      nonceStr: jsapiSignature.value.nonceStr,
      signature: jsapiSignature.value.signature,
      jsApiList: ['getCurExternalContact']
    })
    wx.invoke('getCurExternalContact', {}, function (res) {
      if (res.err_msg == 'getCurExternalContact:ok') {
        wxUserId.value = res.userId
        getUserDetail(res.userId)
      } else {
        ElMessage.error('获取用户Id失败')
      }
    })
  } catch (error) {
    ElMessage.error(error)
  }
}
const customerData = ref(null)
// 3.获取用户详情
const getUserDetail = async (id) => {
  const data = await getWeCustomerId(id)
  customerData.value = data
}
// 转客户绑定客户
const bindCustomer = async (id) => {
  const obj = {
    id: customerData.value.id,
    customerStatus: 1,
    customerId: id
  }
  let data = await bindCustomerApi(obj)
  getUserDetail(wxUserId.value)
}
// 转客户
const tranCustomer = () => {
  customerForm.value.weComOpen('create', customerData.value)
}
/** 同步企微员工 */
const handleSyncUser = async () => {
  const data = await syncUser()
  if (data) {
    Message.success('同步成功')
    getUserDetail(wxUserId.value)
  } else {
    Message.error('同步有误')
  }
}
onMounted(() => {
  getWeComApiConfig()
})
</script>

<style lang="scss" scoped>
.wx_detail {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f4ff 50%, #f8fafc 100%);
  padding: 16px;
  box-sizing: border-box;
  overflow-y: auto;
  overflow-x: hidden;
  position: fixed;
  top: 0;
  left: 0;

  /* 滚动条美化 */
  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f3f4;
    border-radius: 3px;
  }

  &::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #c1c9d2 0%, #a8b4c0 100%);
    border-radius: 3px;
    transition: all 0.2s ease;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #0052cc 0%, #1d4ed8 100%);
    box-shadow: 0 2px 4px rgba(0, 82, 204, 0.3);
  }
}

/* 客户容器 */
.customer-container {
  max-width: 800px;
  margin: 0 auto;
  padding-bottom: 20px;
}

/* 客户信息卡片 */
.customer-info-card {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 82, 204, 0.1);
  overflow: hidden;
  margin-bottom: 20px;
  border: 1px solid rgba(0, 82, 204, 0.1);
}

.card-header {
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  padding: 20px;
  color: white;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-avatar {
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.avatar-icon {
  font-size: 28px;
  color: white;
}

.user-basic-info {
  flex: 1;
}

.user-name {
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 4px 0;
  color: white;
}

.corp-name {
  font-size: 14px;
  margin: 0;
  color: rgba(255, 255, 255, 0.8);
}

.card-body {
  padding: 24px;
}

/* 描述列表样式 */
.custom-descriptions {
  margin-bottom: 20px;
}

.custom-descriptions :deep(.el-descriptions__body) {
  background: transparent;
}

.desc-item :deep(.el-descriptions__label) {
  color: #606266;
  font-weight: 600;
  width: 120px;
  font-size: 14px;
}

.desc-item :deep(.el-descriptions__content) {
  color: #303133;
  font-size: 14px;
}

.user-name-text {
  color: #0052cc;
  font-weight: 600;
}

.corp-text {
  color: #409eff;
}

.time-text {
  color: #909399;
  font-size: 13px;
}

/* 操作按钮 */
.opera-btn {
  display: flex;
  justify-content: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.transfer-btn {
  background: #0052cc;
  border-color: #0052cc;
  padding: 10px 32px;
  border-radius: 8px;
  font-weight: 600;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.transfer-btn:hover {
  background: #003d99;
  border-color: #003d99;
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 82, 204, 0.3);
}

.btn-icon {
  font-size: 16px;
}

/* 跟进记录区域 */
.follow-section {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 82, 204, 0.1);
  overflow: hidden;
  border: 1px solid rgba(0, 82, 204, 0.1);
}

.section-title {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 16px 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #495057;
  border-bottom: 1px solid #e9ecef;
}

.title-icon {
  color: #0052cc;
  font-size: 18px;
}

.follow-list {
  padding: 16px;
}

.follow-item {
  background: #fafbfc;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid #e9ecef;
  transition: all 0.3s ease;
}

.follow-item:hover {
  box-shadow: 0 4px 16px rgba(0, 82, 204, 0.1);
  border-color: rgba(0, 82, 204, 0.2);
}

.follow-item:last-child {
  margin-bottom: 0;
}

.follow-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e9ecef;
}

.follow-user {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar-small {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-icon-small {
  font-size: 18px;
  color: white;
}

.user-info {
  flex: 1;
}

.user-nickname {
  font-size: 15px;
  font-weight: 600;
  margin: 0 0 2px 0;
  color: #303133;
}

.user-level {
  font-size: 12px;
  margin: 0;
  color: #909399;
}

.follow-time {
  font-size: 12px;
  color: #909399;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 4px;
}

/* 跟进内容描述 */
.follow-descriptions :deep(.el-descriptions__body) {
  background: transparent;
}

.follow-desc-item :deep(.el-descriptions__label) {
  color: #606266;
  font-weight: 500;
  width: 100px;
  font-size: 13px;
}

.follow-desc-item :deep(.el-descriptions__content) {
  color: #303133;
  font-size: 13px;
}

.desc-value {
  color: #495057;
}

.level-badge {
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  color: white;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.phone-text {
  color: #0052cc;
  font-weight: 500;
}

.remark-text {
  color: #e67e22;
  font-style: italic;
}

.desc-text {
  color: #6c757d;
  line-height: 1.4;
}

.scene-tag {
  background: #e3f2fd;
  color: #1976d2;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .wx_detail {
    padding: 12px;
  }

  .card-header {
    padding: 16px;
  }

  .header-content {
    gap: 12px;
  }

  .user-avatar {
    width: 50px;
    height: 50px;
  }

  .avatar-icon {
    font-size: 24px;
  }

  .user-name {
    font-size: 18px;
  }

  .corp-name {
    font-size: 13px;
  }

  .card-body {
    padding: 16px;
  }

  .desc-item :deep(.el-descriptions__label) {
    width: 100px;
    font-size: 13px;
  }

  .desc-item :deep(.el-descriptions__content) {
    font-size: 13px;
  }

  .transfer-btn {
    padding: 8px 24px;
    font-size: 13px;
  }

  .section-title {
    padding: 12px 16px;
    font-size: 15px;
  }

  .follow-list {
    padding: 12px;
  }

  .follow-item {
    padding: 12px;
  }

  .follow-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .follow-user {
    width: 100%;
  }

  .follow-time {
    align-self: flex-end;
  }
}

@media (max-width: 480px) {
  .wx_detail {
    padding: 8px;
  }

  .card-header {
    padding: 12px;
  }

  .user-name {
    font-size: 16px;
  }

  .card-body {
    padding: 12px;
  }

  .desc-item :deep(.el-descriptions__label) {
    width: 80px;
    font-size: 12px;
  }

  .desc-item :deep(.el-descriptions__content) {
    font-size: 12px;
  }

  .transfer-btn {
    width: 100%;
    max-width: 200px;
  }

  .follow-desc-item :deep(.el-descriptions__label) {
    width: 80px;
    font-size: 12px;
  }

  .follow-desc-item :deep(.el-descriptions__content) {
    font-size: 12px;
  }
}

/* 动画效果 */
.customer-info-card,
.follow-section {
  animation: fadeInUp 0.6s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
